package com.quectel.core.module.partyeducationexam.service.impl;


import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partyeducationexam.dao.PartyEducationTrainingExamPersonHistoryDao;
import com.quectel.core.module.partyeducationexam.dto.PartyEducationTrainingExamPersonHistoryDto;
import com.quectel.core.module.partyeducationexam.entity.PartyEducationTrainingExamPersonHistoryEntity;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamPersonHistoryService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamPersonService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamQuestionService;
import com.quectel.core.module.partyeducationexam.service.PartyEducationTrainingExamService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/06/30 11:12
 */
@DubboService
public class PartyEducationTrainingExamPersonHistoryServiceImpl implements PartyEducationTrainingExamPersonHistoryService{

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyEducationTrainingExamPersonHistoryServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_EDUCATION_TRAINING_EXAM_PERSON_HISTORY_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_EDUCATION_TRAINING_EXAM_PERSON_HISTORY_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyEducationTrainingExamPersonHistoryDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_EDUCATION_TRAINING_EXAM_PERSON_HISTORY_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    private static final String EXAM_LOCK = "";

    @Autowired
    private PartyEducationTrainingExamPersonHistoryDao partyEducationTrainingExamPersonHistoryDao;
    @Autowired
    private PartyEducationTrainingExamService partyEducationTrainingExamService;
    @Autowired
    private PartyEducationTrainingExamPersonService examPersonService;
    @Autowired
    private PartyEducationTrainingExamPersonService partyEducationTrainingExamPersonService;
    @Autowired
    private PartyEducationTrainingExamQuestionService partyEducationTrainingExamQuestionService;


//    @Override
//    @ServiceLock(
//            lockExpresses = {
//                    RedisLockConstants.TRAINING_EXAM_LOCK + "#{#examSubmitDto.examId}"
//            }
//    )
//    @Transactional
//    public Long saveAndUpdate(ExamSubmitDto examSubmitDto) {
//        PartyEducationTrainingExamDto partyEducationTrainingExamDto = partyEducationTrainingExamService.selectById(examSubmitDto.getExamId());
//        if (partyEducationTrainingExamDto == null) {
//            return null;
//        }
//
//        PartyEducationTrainingExamPersonDto refDto = examPersonService.selectOne(examSubmitDto.getExamId(), examSubmitDto.getPersonId());
//        if (refDto == null) {
//            return null;
//        }
//
//        if (PartyEducationExamPersonConstants.TakeStatusEnum.UNEXAMINED.getStatus().equals(refDto.getTakeStatus())) {
//            PartyEducationTrainingExamDto updateObj = new PartyEducationTrainingExamDto();
//            updateObj.setId(partyEducationTrainingExamDto.getId());
//            updateObj.setExamCompletePersonCount(partyEducationTrainingExamDto.getExamCompletePersonCount() + 1);
//            partyEducationTrainingExamService.updateById(updateObj);
//        }
//
//        List<PartyEducationTrainingExamQuestionDto> examQuestionDtos = partyEducationTrainingExamQuestionService.selectByExamId(examSubmitDto.getExamId());
//        Map<Long, PartyEducationTrainingExamQuestionDto> questionMap = new HashMap<>();
//        for (PartyEducationTrainingExamQuestionDto examQuestionDto : examQuestionDtos) {
//            questionMap.put(examQuestionDto.getQuestionId(), examQuestionDto);
//        }
//        List<PartyEducationTrainingExamQuestionDto> updateObjList = new ArrayList<>();
//        for (PartyEducationQuestionDto question : examSubmitDto.getQuestions()) {
//            PartyEducationTrainingExamQuestionDto partyEducationTrainingExamQuestionDto = questionMap.get(question.getId());
//            if (partyEducationTrainingExamQuestionDto != null) {
//                PartyEducationTrainingExamQuestionDto updateObj = new PartyEducationTrainingExamQuestionDto();
//                updateObj.setId(partyEducationTrainingExamQuestionDto.getId());
//                updateObj.setCompleteCount(partyEducationTrainingExamQuestionDto.getCompleteCount() == null
//                        ? 1 : partyEducationTrainingExamQuestionDto.getCompleteCount() + 1);
//                if (PartyEducationQuestionConstants.GradeEnum.RIGHT.getStatus().equals(question.getGrade())) {
//                    updateObj.setRightCount(partyEducationTrainingExamQuestionDto.getRightCount() == null
//                            ? 1 : partyEducationTrainingExamQuestionDto.getRightCount() + 1);
//                }
//                updateObjList.add(updateObj);
//            }
//        }
//        partyEducationTrainingExamQuestionService.updateBatch(updateObjList);
//
//        BigDecimal score = examSubmitDto.getQuestions().stream().map(PartyEducationQuestionDto::getEntrantScore).reduce(BigDecimal.ZERO, BigDecimal::add);
//        List<EntrantAnswerCls> collect = examSubmitDto.getQuestions().stream().map(o -> {
//            EntrantAnswerCls entrantAnswerCls = new EntrantAnswerCls();
//            entrantAnswerCls.setQuestionId(o.getId());
//            entrantAnswerCls.setGrade(o.getGrade());
//            entrantAnswerCls.setScore(o.getEntrantScore());
//            entrantAnswerCls.setEntrantAnswer(JacksonUtils.parseArray(o.getEntrantAnswer(), String.class).toArray(new String[0]));
//            return entrantAnswerCls;
//        }).collect(Collectors.toList());
//
//        PartyEducationTrainingExamPersonHistoryDto newlyDto = new PartyEducationTrainingExamPersonHistoryDto();
//        newlyDto.setTenantId(partyEducationTrainingExamDto.getTenantId());
//        newlyDto.setPartyId(partyEducationTrainingExamDto.getPartyId());
//        newlyDto.setExamId(partyEducationTrainingExamDto.getId());
//        newlyDto.setPartyPersonId(examSubmitDto.getPersonId());
//        newlyDto.setScore(score);
//        newlyDto.setAnswer(JacksonUtils.toJsonString(collect));
//        newlyDto.setPassStatus(examSubmitDto.getPassStatus());
//        if (!PartyEducationExamPersonConstants.PassStatusEnum.UNRECORDED.getStatus().equals(examSubmitDto.getPassStatus())) {
//            // 审阅完成了
//            newlyDto.setGradePersonName("系统自动");
//            newlyDto.setGradeTime(new Date());
//        }
//        newlyDto.setStartTime(refDto.getLastExamStartTime());
//        newlyDto.setEndTime(examSubmitDto.getSubmitTime());
//        Long save = save(newlyDto);
//
//        PartyEducationTrainingExamPersonDto updateRef = new PartyEducationTrainingExamPersonDto();
//        updateRef.setId(refDto.getId());
//        updateRef.setLastExamEndTime(newlyDto.getEndTime());
//
//        if (!PartyEducationExamPersonConstants.PassStatusEnum.UNRECORDED.getStatus().equals(examSubmitDto.getPassStatus())
//                && !PartyEducationExamPersonConstants.PassStatusEnum.PASSED.getStatus().equals(refDto.getPassStatus())) {
//            updateRef.setPassStatus(examSubmitDto.getPassStatus());
//        }
//        if (!PartyEducationExamPersonConstants.PassStatusEnum.UNRECORDED.getStatus().equals(examSubmitDto.getPassStatus())) {
//            updateRef.setLastScore(newlyDto.getScore());
//            if (refDto.getMaxScore() == null || score.compareTo(refDto.getMaxScore()) > 0) {
//                updateRef.setMaxScore(score);
//            }
//        }
//        updateRef.setLastAnswer(newlyDto.getAnswer());
//        updateRef.setTakeCount(refDto.getTakeCount() + 1);
//        updateRef.setTakeStatus(PartyEducationExamPersonConstants.TakeStatusEnum.EXAMINED.getStatus());
//        updateRef.setLastExamId(save);
//        partyEducationTrainingExamPersonService.updateById(updateRef);
//
//        return save;
//    }

    @Override
    public PartyEducationTrainingExamPersonHistoryDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_EDUCATION_TRAINING_EXAM_PERSON_HISTORY_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyEducationTrainingExamPersonHistoryDto selectById(Long id){
            PartyEducationTrainingExamPersonHistoryEntity entity = partyEducationTrainingExamPersonHistoryDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity,PartyEducationTrainingExamPersonHistoryDto.class));
    }

    @Override
    public List<PartyEducationTrainingExamPersonHistoryDto> queryList(Map<String,Object> params){
        List<PartyEducationTrainingExamPersonHistoryEntity> list = partyEducationTrainingExamPersonHistoryDao.queryList(params);
        List<PartyEducationTrainingExamPersonHistoryDto> result =  CopyUtils.copyList(list,PartyEducationTrainingExamPersonHistoryDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<PartyEducationTrainingExamPersonHistoryDto> queryListWithoutPadding(Map<String,Object> params){
        List<PartyEducationTrainingExamPersonHistoryEntity> list = partyEducationTrainingExamPersonHistoryDao.queryList(params);
        return CopyUtils.copyList(list,PartyEducationTrainingExamPersonHistoryDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyEducationTrainingExamPersonHistoryDto paddingField(PartyEducationTrainingExamPersonHistoryDto dto){
        if (dto != null){

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return partyEducationTrainingExamPersonHistoryDao.queryTotal(params);
    }

    @Override
    public Long save(PartyEducationTrainingExamPersonHistoryDto dto){
        PartyEducationTrainingExamPersonHistoryEntity entity = CopyUtils.copyObj(dto,PartyEducationTrainingExamPersonHistoryEntity.class);
        entity.setId(Snowflake.nextId());
        partyEducationTrainingExamPersonHistoryDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PartyEducationTrainingExamPersonHistoryDto dto){
        PartyEducationTrainingExamPersonHistoryEntity entity = CopyUtils.copyObj(dto,PartyEducationTrainingExamPersonHistoryEntity.class);

        partyEducationTrainingExamPersonHistoryDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PartyEducationTrainingExamPersonHistoryDto dto) {
       PartyEducationTrainingExamPersonHistoryEntity entity = CopyUtils.copyObj(dto,PartyEducationTrainingExamPersonHistoryEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, partyEducationTrainingExamPersonHistoryDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyEducationTrainingExamPersonHistoryDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
